﻿
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Linq;
using SpiderPlatform.Dao;
using SpiderPlatform.Entity;
using Yamibuy.Framework.Core.Tools;
namespace SpiderPlatform.Service
{
    public class RanchService
    {
        string apiService = "https://api.freshop.com/1/products?app_key=99_ranch_market";    
        string token = string.Empty;
        string app_key = "99_ranch_market";
        // string fields = "id,identifier,reference_id,reference_ids,upc,name,store_id,department_id,size,cover_image,price,sale_price,sale_start_date,sale_finish_date,price_disclaimer,sale_price_disclaimer,is_favorite,relevance,popularity,shopper_walkpath,fulfillment_walkpath,quantity_step,quantity_minimum,quantity_initial,quantity_label,quantity_label_singular,varieties,quantity_size_ratio_description,status,status_id,sale_configuration_type_id,fulfillment_type_id,fulfillment_type_ids,other_attributes,clippable_offer,slot_message,call_out,has_featured_offer,tax_class_label,promotion_text,sale_offer,store_card_required,average_rating,review_count,offered_together,sequence";
        string fields = "id,upc,name,store_id,department_id,size,price,sale_price,description,identifier,images,quantity_on_hand";
        ItemDao dao = new ItemDao();

        public DateTime? CurrentDay { get; set; }
        public bool OnlyMail { get; set; }

        public DateTime TodayTime
        {
            get
            {

                DateTime todaytime = DateTime.Today;
                if (CurrentDay.HasValue)
                {
                    todaytime = CurrentDay.Value;
                }
                return todaytime;
            }
        }
        public void doWork()
        {
            token=GetToken();
            var categoryList = GetCategory();
            var totalCate = categoryList.departments[0];
            var cate1 = categoryList.departments.Where(p => p.parent_id == totalCate.id);  
            DownData(categoryList, cate1);     
            Logger.Info("数据导入完成");          
        }
        private string GetToken()
        {
            RanchToken token = new RanchToken();     
            HttpClient client = new HttpClient();
            var res = client.GetAsync($"https://api.freshop.com/2/sessions/8ee2afde191e8b8405d205ba99ff9ab4?app_key={app_key}").Result;
            if (res.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string data = res.Content.ReadAsStringAsync().Result;
                token = Newtonsoft.Json.JsonConvert.DeserializeObject<RanchToken>(data);
            }
            Logger.Info("get token success...");
            return token.token;

        }
        private void DownData(RanchCategoryResult categoryList, IEnumerable<RanchCategory> cate1)
        {
            var all = new List<RanchProduct>();       

            int skip = 0;
            int page_size = 100;
            RanchProductResult res = new RanchProductResult();
            List<RanchProduct> list = new List<RanchProduct>();
            do
            {
                Logger.Info("===》"+ skip);
                res = GetProductList(skip, page_size, fields);
                if (res.items?.Count() > 0)
                {
                    ImportData(res.items);
                }
                skip += page_size;          
            }
            while (res.items?.Count() > 0);     
            Logger.Info("===》数据抓取完成");
        }

        private void ImportData(RanchProduct[] list)
        {         
            List<ChannelItemHistoryEntity> hisList = new List<ChannelItemHistoryEntity>();
            foreach (var item in list)
            {               
               
                hisList.Add(new ChannelItemHistoryEntity
                {
                    channel_id = 3,
                    channel_sku = item.id,
                    score = 0,
                    is_instock = item.quantity_on_hand,
                    reviews = 0,
                    price = decimal.Parse(item.price.TrimStart('$')),
                    title = item.name,
                    link = item.link,
                    images =item.imageInfo,
                    description=item.description
                   
                });
            }
            Logger.Info($"开始导入商品信息...，共{hisList.Count}条");
            dao.CreateChannelItemHistory(hisList);
            var hisExists = dao.QueryChannelItemBySku(3, hisList.Select(p => p.channel_sku).ToList());
            //检查是否有新的商品出现
            var diffList = hisList.Except(hisExists, new ChannelItemHistoryComparer());
            //记录新的item   
            var newItemList = diffList.ToList().ToTypeList<ChannelItemHistoryEntity, ChannelItemEntity>();
            Logger.Info($"检查新商品...，共{newItemList.Count}条");
            if (newItemList.Count > 0)
            {
                Logger.Info($"导入新商品step1...");
                dao.CreateChannelItem(newItemList);
                var realList = diffList.ToList();
                Logger.Info($"导入新商品step2...");
                dao.CreateChannelItemRealTime(realList);
            }
            Logger.Info($"更新商品信息...");
            dao.UpdateChannelItemRealTime(hisList);       
        }
        private RanchCategoryResult GetCategory()
        {
            RanchCategoryResult result = new RanchCategoryResult();
            HttpClient client = new HttpClient();
            var res = client.GetAsync($"{apiService}&department_id_cascade=true&include_departments=true&include_offered_together=true&limit=0&render_id=1560477405201&store_id=3122&token={token}").Result;
            if (res.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string data = res.Content.ReadAsStringAsync().Result;
                result = Newtonsoft.Json.JsonConvert.DeserializeObject<RanchCategoryResult>(data);
            }
            return result;
        }

        private RanchProductResult GetProductList(int skip, int limit, string fields)
        {
            RanchProductResult result = new RanchProductResult();
            HttpClient client = new HttpClient();
            //var res = client.GetAsync($"{apiService}&department_id={department_id}&department_id_cascade=true&skip={skip}&fields={fields}&include_offered_together=true&limit={limit}&popularity_sort=asc&render_id=1560477405201&sort=popularity&store_id=3122&token={token}").Result;
            var res = client.GetAsync($"{apiService}&department_id_cascade=true&skip={skip}&fields={fields}&include_offered_together=true&limit={limit}&popularity_sort=asc&render_id=1560477405201&sort=popularity&store_id=3122&token={token}").Result;
            if (res.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string data = res.Content.ReadAsStringAsync().Result;
                result = Newtonsoft.Json.JsonConvert.DeserializeObject<RanchProductResult>(data);
            }
            return result;
        }      
    }
}
